package com.health.viewscontrols.medical.device.bg;

import android.app.AlertDialog;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.viewscontrols.FWMYDPJActivity;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.health.viewscontrols.tijian.YBQK_ZiLiWenJuanActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.sinocare.multicriteriasdk.MulticriteriaSDKManager;
import com.sinocare.multicriteriasdk.auth.AuthStatusListener;
import com.sinocare.multicriteriasdk.utils.AuthStatus;
import com.vivachek.protocol.BaseResult;
import com.vivachek.protocol.Parse;
import com.vivachek.protocol.ParseListener;
import com.vivachek.protocol.enums.TestStatusEnums;
import com.vivachek.protocol.enums.UnitEnums;
import com.vivachek.protocol.enums.WarnCodeEnums;
import com.vivachek.protocol.utils.CommandUtil;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * 百捷三合一
 */
public class VivaActivity extends BaseDeviceActivity implements ParseListener {

    public final static String UUID_SERVICE = "0003cdd0-0000-1000-8000-00805f9b0131";
    public final static String UUID_NOTIFY = "0003cdd1-0000-1000-8000-00805f9b0131";
    public final static String UUID_WRITE = "0003cdd2-0000-1000-8000-00805f9b0131";
    // 每次连接设备成功后,强烈建议主动发送获取单位和设置设备时间指令.否则在检测过程中设备不会发出对应指令协议.
    private String bgUnitCommand = "7B01100120AA55000002010D087D";
    private String bgSetTimeCommand = "7B011001204466000615041C09051E0C02030F7D";
    // 获取历史数据
    private String historyCommand = "7B01100120DD550000030A060C7D";
    // 删除历史数据
    private String deleteHistoryCommand = "7B0110012055660001110C020D047D";

    private boolean getDataStatus = false;


    private BleDevice fastBleDevice;
    private BigDecimal jcresult = new BigDecimal(0l);

    private Context context;

    Timer timer;
    TimerTask task;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            cancelProgressDialog();
            connDevice();
        }
    };

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.viva);



        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 15000)
                .setConnectOverTime(20000)
                .setOperateTimeout(15000);

        bt_delete_history.setVisibility(View.VISIBLE);
        bt_data.setVisibility(View.VISIBLE);
        bt_data.setText("同步数据");

        bt_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                syncDataList.clear();
                getDataStatus = true;
                if (fastBleDevice != null) {
                    asynFn();
                } else {
                    connDevice();
                }
            }
        });

        bt_delete_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(VivaActivity.this).setTitle("删除历史数据").setMessage("确定要删除设备历史数据吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (fastBleDevice != null) {
                                        getDataStatus = false;
                    //                    byte[] bytes = CommandUtil.INSTANCE.generateCmd(85, 102, 0, 1, new ArrayList<Integer>());
                    //                    String hexString = HexUtil.formatHexString(bytes);
                                        write(fastBleDevice, deleteHistoryCommand);
                                        ToastUtils.showShort("删除成功");
                                    }
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
//                if (fastBleDevice != null) {
//                    getDataStatus = false;
////                    byte[] bytes = CommandUtil.INSTANCE.generateCmd(85, 102, 0, 1, new ArrayList<Integer>());
////                    String hexString = HexUtil.formatHexString(bytes);
//                    write(fastBleDevice, deleteHistoryCommand);
//                    ToastUtils.showShort("删除成功");
//                }
            }
        });

        Parse.INSTANCE.setParseListener(this);
    }

    private void asynFn() {
        try {
            byte[] bytes = CommandUtil.INSTANCE.generateCmd(221, 85, 0, 0, new ArrayList<Integer>());
            String hexString = HexUtil.formatHexString(bytes);
            write(fastBleDevice, hexString);
            getDataStatus = true;
            showDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startDevice() {
        getDataStatus = false;
        connDevice();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        };
        timer.schedule(task, 6000);
    }

    private void connDevice() {
        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle(), true);
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    Log.e(TAG, "onScanning: " + bleDevice.getName() + "  " + bleDevice.getMac());
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            cancelProgressDialog();
//            showProgressDialog("等待接收数据");
        }
    }

    private void connectionPwBle() {
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " + exception.toString());
                blueToothState.setText("蓝牙连接失败");
                connectionPwBle();
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac());
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                cancelProgressDialog();
//                showProgressDialog("等待接收数据");

//                // 删除历史数据
//                write(fastBleDevice, deleteHistoryCommand);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                }, 200);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
                disconnectDevice();
                cancelProgressDialog();
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE.toString(),
                UUID_NOTIFY.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: ");

                        if (getDataStatus) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    asynFn();
                                }
                            }, 500);
                        } else {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    write(fastBleDevice, bgUnitCommand);
                                }
                            }, 500);

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        byte[] bytes = CommandUtil.INSTANCE.generateCmd(68, 102, 0, 6, new ArrayList<Integer>());
                                        String hexString = HexUtil.formatHexString(bytes);
//                        write(fastBleDevice, bgSetTimeCommand);
                                        write(fastBleDevice, hexString);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, 800);
                        }
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " + exception.toString());
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getPwNotify(bleDevice);
                            }
                        }, 500);
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "Notify: " + hexString);
                        Log.e(TAG, "getDataStatus: " + getDataStatus);
                        if (getDataStatus) {
                            syncData(data);
                        } else {
                            formatData(data);
                        }
                    }
                });
    }

    private void write(BleDevice bleDevice, String common) {
        byte[] bytes = hexStringToByteArray(common);
        BleManager.getInstance().write(bleDevice, UUID_SERVICE,
                UUID_WRITE, bytes, new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        Log.e(TAG, "beitai onWriteSuccess: ");
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        Log.e(TAG, " beitaionWriteFailure: " + exception.toString());
                    }
                });
    }

    /**
     * 16进制字符串转字节数组
     */
    public static byte[] hexStringToByteArray(String digits) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            for (int i = 0; i < digits.length(); i += 2) {
                char c1 = digits.charAt(i);
                if ((i + 1) >= digits.length()) {
                    throw new IllegalArgumentException("hexUtil.odd");
                }
                char c2 = digits.charAt(i + 1);
                byte b = 0;
                if ((c1 >= '0') && (c1 <= '9'))
                    b += ((c1 - '0') * 16);
                else if ((c1 >= 'a') && (c1 <= 'f'))
                    b += ((c1 - 'a' + 10) * 16);
                else if ((c1 >= 'A') && (c1 <= 'F'))
                    b += ((c1 - 'A' + 10) * 16);
                else
                    throw new IllegalArgumentException("hexUtil.bad");

                if ((c2 >= '0') && (c2 <= '9'))
                    b += (c2 - '0');
                else if ((c2 >= 'a') && (c2 <= 'f'))
                    b += (c2 - 'a' + 10);
                else if ((c2 >= 'A') && (c2 <= 'F'))
                    b += (c2 - 'A' + 10);
                else
                    throw new IllegalArgumentException("hexUtil.bad");
                baos.write(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return (baos.toByteArray());
    }

    @Override
    public void update(String hexStr) {
        Log.e(TAG, "update: " + hexStr);

        try {
            byte[] data = HexUtil.hexStringToBytes(hexStr);
            formatData(data);
            Log.e(TAG, "update: " + data.length);
            disconnectDevice();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void formatData(byte[] data) {
        //接收数据
        try {
            String formatHexString1 = HexUtil.formatHexString(data);
            Log.e(TAG, "formatData: " + formatHexString1);
            if (formatHexString1.length() < 24) {
                return;
            }
            String type = formatHexString1.substring(18, 20);
            String data1 = formatHexString1.substring(20, 22);

            String data2 = formatHexString1.substring(22, 24);
            Log.e(TAG, "formatData: " + type);
            int result = Integer.parseInt(data1, 16) * 100 + Integer.parseInt(data2, 16);
            switch (type) {
                case "44":
                    //血糖
                    BigDecimal bg = new BigDecimal(result / 10.0);
                    tv_result.setText("血糖测量结果：\n        " + bg.setScale(2, BigDecimal.ROUND_HALF_UP) + "mmol/L");
                    if (jcresult.compareTo(bg.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                        return;
                    }
                    jcresult = bg.setScale(2, BigDecimal.ROUND_HALF_UP);
                    Log.e("xiaoxin", "测量结果: " + "--" + jcresult);
                    tv_state.setText("获取测量结果成功");
                    tv_result.setText("血糖值： " + jcresult + "mmol/L");
                    DeviceShowSaveData.getDataShow(jcresult + "", "BeneCheck");
                    DeviceShowSaveData.saveXuetangBj(jcresult + "");
                    cancelProgressDialog();
                    break;
                case "dd":
                case "DD":
                    //尿酸设备
                    BigDecimal ns = new BigDecimal(result / 100.0);
                    tv_result.setText("尿酸测量结果：\n        " + ns.setScale(2, BigDecimal.ROUND_HALF_UP) + "µmol/L");
                    if (jcresult.compareTo(ns.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                        return;
                    }
                    jcresult = ns.setScale(2, BigDecimal.ROUND_HALF_UP);
                    tv_state.setText("获取测量结果成功");
                    tv_result.setText("尿酸值： " + jcresult + "µmol/L");
                    Log.e("xiaoxin", "尿酸设备测量结果: " + "--" + jcresult);
                    DeviceShowSaveData.getDataShow(jcresult + "", "BeneCheck-ns");
                    DeviceShowSaveData.saveNs(jcresult + "");
                    cancelProgressDialog();
                    break;
                case "99":
                    // 血酮
                    BigDecimal xt = new BigDecimal(result / 100.0);
                    tv_result.setText("血酮测量结果：\n        " + xt.setScale(2, BigDecimal.ROUND_HALF_UP) + "mmol/L");
                    if (jcresult.compareTo(xt.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                        return;
                    }
                    jcresult = xt.setScale(2, BigDecimal.ROUND_HALF_UP);
                    tv_state.setText("获取测量结果成功");
                    tv_result.setText("血酮值： " + jcresult + "mmol/L");
                    Log.e("xiaoxin", "血酮设备测量结果: " + "--" + jcresult);
                    DeviceShowSaveData.getDataShow(jcresult + "", "BeneCheck-xuetong");
                    DeviceShowSaveData.saveDgc(jcresult + "");
                    cancelProgressDialog();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
            if (fastBleDevice != null) {
                BleManager.getInstance().stopNotify(fastBleDevice, UUID_SERVICE.toString(), UUID_NOTIFY.toString());
                //断开设备
                BleManager.getInstance().disconnectAllDevice();
                BleManager.getInstance().destroy();
                fastBleDevice = null;
            }
            BleManager.getInstance().cancelScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (timer != null) {
                timer.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void syncData(byte[] data) {
        if (data == null) {
            return;
        }

        List<Integer> convert = new ArrayList<>();
        for (byte b : data) {
            convert.add((b & 0xFF));
        }

        Parse.INSTANCE.process(convert);
    }

    private ListDialogFragment listDialog;
    private List<BaseResult> syncDataList = new ArrayList<>();

    private void showDialog() {
        showProgressDialog("正在获取数据");
        listDialog = ListDialogFragment.newInstance(syncDataList);
        listDialog.setOnItemSelectedListener(item -> {
            // 处理用户选择的数据
            String desc = item.getSample().getDesc();
            String value = item.getValue();
            if (desc.contains("血糖")) {
                tv_result.setText("血糖值：\n        " + value + " " + item.getUnitEnum().getUnit());
                tv_state.setText("获取测量结果成功");
                DeviceShowSaveData.getDataShow(value + "", "BeneCheck");
                DeviceShowSaveData.saveXuetangBj(value + "");
            } else if (desc.contains("血酮")) {
                tv_state.setText("获取测量结果成功");
                tv_result.setText("血酮值：\n        " + value + " " + item.getUnitEnum().getUnit());
                DeviceShowSaveData.getDataShow(value + "", "BeneCheck-xuetong");
                DeviceShowSaveData.saveDgc(value + "");
            } else if (desc.contains("尿酸")) {
                tv_state.setText("获取测量结果成功");
                tv_result.setText("尿酸值：\n        " + value + " " + item.getUnitEnum().getUnit());
                DeviceShowSaveData.getDataShow(value + "", "BeneCheck-ns");
                DeviceShowSaveData.saveNs(value + "");
            }
            getDataStatus = false;
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                cancelProgressDialog();
                if (syncDataList != null && syncDataList.size() <= 0) {
                    ToastUtils.showShort("暂无历史数据");
                } else {
                    listDialog.show(getFragmentManager(), "list_dialog");
                }
            }
        }, 2500);
    }

    // 更新数据的方法
    private void updateDialogData(BaseResult baseResult) {
        syncDataList.add(baseResult);
//        if (listDialog != null) {
//            listDialog.updateData(syncDataList);
//        }
    }

    @Override
    public void sn(@NotNull String sn) {

    }

    @Override
    public void unit(@NotNull UnitEnums unit) {

    }

    @Override
    public void setTimeSuccess(boolean success) {

    }

    @Override
    public void deviceTime(@NotNull String time) {

    }

    @Override
    public void status(@NotNull TestStatusEnums statusEnums) {

    }

    @Override
    public void lastTestResult(@NotNull BaseResult baseResult) {

    }

    @Override
    public void warn(@NotNull WarnCodeEnums warnCodeEnums) {

    }

    @Override
    public void result(@NotNull BaseResult result) {

    }

    @Override
    public void historyGlucose(@NotNull BaseResult result) {
        Log.e(TAG, "historyGlucose: " + result.toString());
        updateDialogData(result);
    }

    @Override
    public void historyFinish() {

    }

    @Override
    public void deviceSoftwareVersion(@NotNull String version) {

    }

    @Override
    public void devicePowerOff() {

    }

    @Override
    public void deleteHistorySuccess() {

    }

    @Override
    public void codeChip(int number) {

    }

    @Override
    public void needReply() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Parse.INSTANCE.removeListener();
    }
}
